//
//  NewsParser.m
//  SlowLoad
//
//  Created by Hai Nguyen on 8/28/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "NewsParser.h"

#define ItemNode @"item"
#define TitleNode @"title"
#define DescriptionNode @"description"
#define LinkNode @"link"
#define PublishDateNode @"pubDate"

@implementation NewsParser
@synthesize arrayNews;
@synthesize currentString;
@synthesize delegate;
@synthesize respondData;
@synthesize  isNews;
@synthesize news;

-(void) getNewsFromUrl:(NSString*) rssUrl withDelegate:(id) theDelegate{
	self.delegate = theDelegate;
	self.respondData = [[[NSMutableData alloc] init] autorelease];
	NSURL *url = [NSURL URLWithString:[rssUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
	NSURLRequest *request = [NSURLRequest requestWithURL:url];
	[[NSURLConnection alloc] initWithRequest:request delegate:self];
}

-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
	//Bat dau nhan dc byte dau tien cua file xml
	[self.respondData setLength:0];
}

-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
	//Da load xong file xml
	[self.respondData appendData:data];
}

-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
	NSLog(@"Error : %@", error);
}

-(void) connectionDidFinishLoading:(NSURLConnection *)connection{
	//ket thuc qua trinh request len rss link
	self.isNews = NO;
	self.currentString = [[[NSMutableString alloc] init] autorelease];
	self.arrayNews = [[[NSMutableArray alloc] init] autorelease];
	NSXMLParser *parser = [[NSXMLParser alloc] initWithData:self.respondData];
	parser.delegate = self;
	[parser parse];
	[parser release];
}

-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
	//tim thay 1 tag xml
	if([elementName isEqualToString:ItemNode]){
		self.isNews = YES;
		self.news = [[[News alloc] init] autorelease];
	}
}

-(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
	//ham nay dc goi moi khi parser doc duoc 1 tu (word) trong file xml
	[self.currentString appendString:string];
	NSLog(@"Current String %@:", string);
}

-(void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
	if (self.isNews) {
		NSString *string = [NSString stringWithFormat:@"%@", self.currentString];
		if ([elementName isEqualToString:TitleNode]) {
			self.news.title = string;
		}
		if ([elementName isEqualToString:LinkNode]) {
			self.news.link = string;
		}
		if ([elementName isEqualToString:DescriptionNode]) {
			NSString *descString = [NSString stringWithFormat:@"%@",string];	
			NSArray *imgTempArray1 = [descString componentsSeparatedByString:@"src=\""];
			if ([imgTempArray1 count]>1) {
				NSArray *imgTempArray2 = [[imgTempArray1 objectAtIndex:1] componentsSeparatedByString:@"\">"];
				self.news.thumbnailLink = [imgTempArray2 objectAtIndex:0];
				if ([imgTempArray2 count]>1) {
					NSArray *descTempArray1 = [[imgTempArray1 objectAtIndex:1] componentsSeparatedByString:@"a>"];
					if ([imgTempArray2 count] > 2) {
						self.news.description = [[NSArray arrayWithArray:[[descTempArray1 objectAtIndex:1]componentsSeparatedByString:@"<BR"]] objectAtIndex:0];
					}
					else{
						self.news.description = [[NSArray arrayWithArray:[[descTempArray1 objectAtIndex:1]componentsSeparatedByString:@"]"]] objectAtIndex:0];
					}
				}				
			}
			else {
				NSArray *descTempArray3 = [descString componentsSeparatedByString:@"<"]; 
				if ([descTempArray3 count]>1) {
					self.news.description = [descTempArray3 objectAtIndex:0];
				}
				else {
					self.news.description = [[NSArray arrayWithArray:[descString componentsSeparatedByString:@"]"]] objectAtIndex:0];
				}
				self.news.thumbnailLink = @"";
			}
		}
		if ([elementName isEqualToString:PublishDateNode]) {
			self.news.publishDate =  string;
		}
		if ([elementName isEqualToString:ItemNode]) {
			self.isNews = NO;
			[self.arrayNews addObject:self.news];
			self.news = nil;
		}
	}
	[self.currentString setString:@""];
}

-(void) parserDidEndDocument:(NSXMLParser *)parser{
	if ([self.delegate respondsToSelector:@selector(didEndGetNews:)]) {
		[self.delegate didEndGetNews:self.arrayNews];
	}else {
		NSLog(@"Parse Errot");
	}
}

-(void) dealloc{
	self.arrayNews = nil;
	self.currentString = nil;
	self.news = nil;
	self.respondData = nil;
	[super dealloc];
}

@end
